package ren.colorful.learnjdk;

import java.lang.reflect.Field;

import sun.misc.Unsafe;

public class LearnUnsafe {
	private static Unsafe unsafe;
	
	//通过反射的方式获取Unsafe实例,直接获取不成功，因为不收信任
	static {
		try {
			Field field = Unsafe.class.getDeclaredField("theUnsafe");
			field.setAccessible(true);
			unsafe = (Unsafe) field.get(null);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public static void main(String[] args) throws Exception {
		Class clazz = Target.class;
		Field[] fields = clazz.getDeclaredFields();
		System.out.println("fieldName:fieldOffset");
		for (Field f : fields) {
			//获取属性偏移量,可以通过这个偏移量给属性设值
			System.out.println(f.getName() + " : " + unsafe.objectFieldOffset(f));
		}
		Target target = new Target();
		Field intField = clazz.getDeclaredField("intParam");
		int a = (Integer)intField.get(target);
		System.out.println("原始值是 : " + a);
		//intParam的字段偏移是12 原始值是3 我们要改成10
		System.out.println(unsafe.compareAndSwapInt(target, 12, 3, 10));
		int b = (Integer)intField.get(target);
		System.out.println("改变之后的值: " + b);
		//现在已经是10了,所以会返回false
		System.out.println(unsafe.compareAndSwapInt(target, 12, 3, 10));
		System.out.println(unsafe.compareAndSwapObject(target, 24, null, "5"));
		System.out.println(target.strParam);
	}
}


class Target{
	int intParam = 3;
	long longParam;
	String strParam;
	String strParam2;
}